#include "DeviceCard.h"
#include "ui_DeviceCard.h"
#include "Tools/UiUpdateMediator.h"
#include "Tools/MyUrl.h"
#include "Tools/MqttClient.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

DeviceCard::DeviceCard(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DeviceCard)
{
    ui->setupUi(this);
    this->InitStyle();
}

DeviceCard::DeviceCard(DeviceInformation *device, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DeviceCard)
{

    ui->setupUi(this);
    this->InitStyle();

    this->device_info = new DeviceInformation(
        device->m_deviceId,
        device->m_username,
        device->m_createTime,
        device->m_creator,
        device->m_connectionStatus,
        device->m_isEnabled
    );

    this->ui->lineEdit_deviceId->setToolTip(device->m_deviceId);
    this->ui->lineEdit_deviceName->setToolTip(device->m_username);
    this->ui->lineEdit_createTime->setToolTip(device->m_createTime);

    this->ui->lineEdit_deviceId->setText(device->m_deviceId);
    this->ui->lineEdit_deviceName->setText(device->m_username);
    this->ui->lineEdit_createTime->setText(device->m_createTime);

    this->ui->lineEdit_createTime->setReadOnly(true);
    this->ui->lineEdit_deviceId->setReadOnly(true);
    this->ui->lineEdit_deviceName->setReadOnly(true);

    if(device->m_connectionStatus == 1)
    {
        device->m_connectionStatus = 0;

        this->ui->label_status->setText("在线");
        this->ui->label_status->setStyleSheet(this->greenFontLabel);

        this->ui->pushButton_connect->setText("断开");
        this->ui->pushButton_connect->setStyleSheet(this->redButtonStyle);


    }
    else
    {
        device->m_connectionStatus = 1;

        this->ui->label_status->setText("离线");
        this->ui->label_status->setStyleSheet(this->redFontLabel);

        this->ui->pushButton_connect->setStyleSheet("连接");
        this->ui->pushButton_connect->setStyleSheet(this->greenButtonStyle);
    }

    if(device->m_isEnabled == 1)
    {
        device->m_isEnabled = 0;

        this->ui->label_isEnabled->setText("使用中");
        this->ui->label_isEnabled->setStyleSheet(this->greenFontLabel);

        this->ui->pushButton_setState->setText("禁用");
        this->ui->pushButton_setState->setStyleSheet(this->redButtonStyle);

        QJsonObject payload;
        payload["device_id"] = this->device_info->m_deviceId;
        payload["command"] = "is_enabled=0";
        QJsonDocument doc(payload);
        qDebug() << doc;
        qDebug() << this->device_info->m_deviceId;
        MqttClient::getInstance().m_client->publish(QMqttTopicName("IOT_DM/command"), doc.toJson(QJsonDocument::Compact), 1, false);
    }
    else
    {
        device->m_isEnabled = 1;

        this->ui->label_isEnabled->setText("禁用中");
        this->ui->label_isEnabled->setStyleSheet(this->redFontLabel);

        this->ui->pushButton_setState->setText("启用");
        this->ui->pushButton_setState->setStyleSheet(this->greenButtonStyle);

        QJsonObject payload;
        payload["device_id"] = this->device_info->m_deviceId;
        payload["command"] = "is_enabled=1";
        QJsonDocument doc(payload);
        MqttClient::getInstance().m_client->publish(QMqttTopicName("IOT_DM/command"), doc.toJson(QJsonDocument::Compact), 1, false);
    }
}

void DeviceCard::on_pushButton_delete_clicked()
{
    QMessageBox::StandardButton result = showDeleteConfirmBox(this, this->ui->lineEdit_deviceId->text());

    if(result == QMessageBox::Yes)
    {
        QNetworkAccessManager* manager = new QNetworkAccessManager();
        connect(manager, &QNetworkAccessManager::finished, this,[=](QNetworkReply* reply){
            int stateCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            if(stateCode == 200)
            {
                qDebug() << "设备删除成功" + this->ui->lineEdit_deviceId->text() << __LINE__ << __FILE_NAME__;
                emit UiUpdateMediator::getInstance()->updateAuthentication();
                emit UiUpdateMediator::getInstance()->updateDevice();
            }
        });

        QJsonObject jsonData;
        jsonData["device_id"] = this->ui->lineEdit_deviceId->text();
        QJsonDocument doc(jsonData);
        qDebug() << jsonData;
        qDebug() << MyUrl::deviceDelete;
        QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::deviceDelete));
        request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        manager->post(*request, doc.toJson(QJsonDocument::Compact));
    }
}

QMessageBox::StandardButton DeviceCard::showDeleteConfirmBox(QWidget *parent, const QString &deviceId)
{
    // 1. 创建弹窗并设置基础信息
    QMessageBox msgBox(parent);
    msgBox.setWindowTitle("确认删除");
    QIcon icon("E:/ComplexProject/IOT_DM/IOT_DM_Client/IOT_DM/Resources/warning.svg");
    msgBox.setIconPixmap(icon.pixmap(48, 48));

    msgBox.setStyleSheet(R"(
    QMessageBox {
        background-color: #ffffff; /* 弹窗背景色 */
        color: #333333; /* 文字色，避免白色文字在白色背景上看不见 */
    }
    QMessageBox QLabel {
        color: #333333; /* 确保标签文字可见 */
    }
    QMessageBox QPushButton {
        /* 按钮样式（保持之前的胶囊样式） */
        border-radius: 18px;
        min-width: 80px;
        height: 36px;
    }
)");
    // 2. 设置内容（标题+说明，清晰传递后果）
    QString content = QString("<span style='font-size:16px; font-weight:500; color:#333;'>确定要删除设备「%1」吗？</span><br/><br/>"
                              "<span style='font-size:14px; color:#666;'>删除后设备数据将无法恢复，请谨慎操作。</span>").arg(deviceId);
    msgBox.setText(content);
    msgBox.setTextFormat(Qt::RichText); // 启用富文本，实现文字样式区分

    // 3. 自定义按钮（取消+删除，颜色区分操作性质）
    QPushButton *cancelBtn = msgBox.addButton("取消", QMessageBox::NoRole);
    QPushButton *deleteBtn = msgBox.addButton("删除", QMessageBox::YesRole);

    // 4. 按钮样式（与之前的胶囊按钮风格统一）
    QString btnStyle = R"(
        QPushButton {
            border-radius: 18px;
            min-width: 80px;
            height: 36px;
            font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
            font-size: 14px;
            border: none;
        }
        /* 取消按钮：浅灰，弱化视觉权重 */
        QPushButton[text="取消"] {
            background-color: #f5f5f5;
            color: #555;
        }
        QPushButton[text="取消"]:hover {
            background-color: #eeeeee;
        }
        /* 删除按钮：红色，强化警告属性 */
        QPushButton[text="删除"] {
            background-color: #f76c5e;
            color: white;
        }
        QPushButton[text="删除"]:hover {
            background-color: #f98274;
        }
    )";
    cancelBtn->setStyleSheet(btnStyle);
    deleteBtn->setStyleSheet(btnStyle);

    // 5. 设置弹窗大小和字体（避免内容挤压）
    msgBox.setFixedSize(400, 200); // 固定尺寸，保证显示一致性
    QFont msgFont = msgBox.font();

    msgBox.setFont(msgFont);

    // 6. 显示弹窗并返回用户选择
    msgBox.exec();
    if (msgBox.clickedButton() == deleteBtn)
    {
        return QMessageBox::Yes; // 用户选择删除
    }
    else
    {
        return QMessageBox::No;  // 用户选择取消
    }
}

DeviceCard::~DeviceCard()
{
    delete ui;
}

void DeviceCard::on_pushButton_edit_clicked()
{
    if(this->ui->pushButton_edit->text() == "编辑")
    {
        this->ui->pushButton_edit->setText("保存");
        this->ui->lineEdit_deviceId->setReadOnly(false);
        this->ui->lineEdit_deviceName->setReadOnly(false);
        this->ui->lineEdit_createTime->setReadOnly(false);
        this->ui->lineEdit_deviceId->setFocus();
    }
    else
    {
        this->ui->lineEdit_deviceId->setReadOnly(true);
        this->ui->lineEdit_deviceName->setReadOnly(true);
        this->ui->lineEdit_createTime->setReadOnly(true);
        this->ui->pushButton_edit->setText("编辑");

        if(this->ui->lineEdit_deviceId->text() == this->device_info->m_deviceId &&
           this->ui->lineEdit_deviceName->text() == this->device_info->m_username &&
           this->ui->lineEdit_createTime->text() == this->device_info->m_createTime)
        {
            return;
        }
        else
        {
            QNetworkAccessManager* manager = new QNetworkAccessManager();
            connect(manager, &QNetworkAccessManager::finished, this,[=](QNetworkReply* reply){
                int stateCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
                if(stateCode == 200)
                {
                    qDebug() << "设备修改成功" + this->ui->lineEdit_deviceId->text() << __LINE__ << __FILE_NAME__;
                    emit UiUpdateMediator::getInstance()->updateDevice();
                    emit UiUpdateMediator::getInstance()->updateAuthentication();
                }
            });

            QJsonObject jsonData;
            jsonData["device_id"] = this->device_info->m_deviceId;
            jsonData["new_device_id"] = this->ui->lineEdit_deviceId->text();
            jsonData["new_username"] = this->ui->lineEdit_deviceName->text();
            jsonData["new_create_time"] = this->ui->lineEdit_createTime->text();

            QJsonDocument doc(jsonData);
            QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::deviceUpdate));
            request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
            manager->post(*request, doc.toJson(QJsonDocument::Compact));
        }
    }
}

void DeviceCard::InitStyle()
{
    this->greenButtonStyle = R"(
        QPushButton {
            background-color: white;
            border: 1.5px solid #52c41a;
            border-radius: 20px;
            padding: 5px 20px;
            color: #52c41a;
            font-size: 14px;
            font-weight: 500;
        }

        QPushButton:hover {
            background-color: #f5f5f5;
            border-color: #4cae4c;

        }

        QPushButton:pressed {
            background-color: #e8e8e8;
            border-color: #3d9e3d;

        }

        QPushButton:disabled {
            background-color: white;
            border-color: #d9d9d9;
            color: #bfbfbf;
        }
    )";

    this->redButtonStyle = R"(
        QPushButton {
            background-color: white;
            border: 1.5px solid #ff4d4f;
            border-radius: 20px;
            padding: 5px 20px;
            color: #ff4d4f;
            font-size: 14px;
            font-weight: 500;
        }

        QPushButton:hover {
            background-color: #f5f5f5;
            border-color: #f5222d;
        }

        QPushButton:pressed {
            background-color: #e8e8e8; /* 与绿色按钮相同的按下灰色 */
            border-color: #d91e18;
        }

        QPushButton:disabled {
            background-color: white;
            border-color: #d9d9d9;
            color: #bfbfbf;
        }
    )";

    this->greenFontLabel = R"(
            QLabel {
            font-family: "Segoe UI", "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
            font-size: 16px;
            font-weight: 400;
            color: #03DE6D;
            line-height: 1.6;
            text-align: left;
            padding: 2px 4px;
            background-color: transparent;
        }

        QLabel:disabled {
            color: #b0b0b0;
        }
    )";

    this->redFontLabel = R"(
            QLabel {
            font-family: "Segoe UI", "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
            font-size: 16px;
            font-weight: 400;
            color: #DE5332;
            line-height: 1.6;
            text-align: left;
            padding: 2px 4px;
            background-color: transparent;
        }

        QLabel:disabled {
            color: #b0b0b0;
        }
    )";
}

void DeviceCard::on_pushButton_connect_clicked()
{
    if(this->ui->pushButton_connect->text() == "连接")
    {
        this->ui->pushButton_connect->setText("断开");
        this->ui->pushButton_connect->setStyleSheet(this->redButtonStyle);
        this->ui->label_status->setText("在线");
        this->ui->label_status->setStyleSheet(this->greenFontLabel);

        QJsonObject payload;
        payload["device_id"] = this->device_info->m_deviceId;
        payload["command"] = "status=1";
        QJsonDocument doc(payload);
        qDebug() << doc;
        qDebug() << this->device_info->m_deviceId;
        MqttClient::getInstance().m_client->publish(QMqttTopicName("IOT_DM/command"), doc.toJson(QJsonDocument::Compact), 1, false);
    }
    else
    {
        this->ui->pushButton_connect->setText("连接");
        this->ui->pushButton_connect->setStyleSheet(this->greenButtonStyle);
        this->ui->label_status->setText("离线");
        this->ui->label_status->setStyleSheet(this->redFontLabel);

        QJsonObject payload;
        payload["device_id"] = this->device_info->m_deviceId;
        payload["command"] = "status=0";
        QJsonDocument doc(payload);
        qDebug() << doc;
        qDebug() << this->device_info->m_deviceId;
        MqttClient::getInstance().m_client->publish(QMqttTopicName("IOT_DM/command"), doc.toJson(QJsonDocument::Compact), 1, false);
    }

    // QNetworkAccessManager* manager = new QNetworkAccessManager();
    // connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply){
    //     int stateCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    //     if(stateCode == 200)
    //     {
    //         if(this->ui->pushButton_connect->text() == "连接")
    //         {
    //             this->ui->pushButton_connect->setText("断开");
    //             this->ui->pushButton_connect->setStyleSheet(this->redButtonStyle);
    //             this->ui->label_status->setText("在线");
    //             this->ui->label_status->setStyleSheet(this->greenFontLabel);


    //         }
    //         else
    //         {
    //             this->ui->pushButton_connect->setText("连接");
    //             this->ui->pushButton_connect->setStyleSheet(this->greenButtonStyle);
    //             this->ui->label_status->setText("离线");
    //             this->ui->label_status->setStyleSheet(this->redFontLabel);
    //         }

    //         qDebug() << "设备修改成功" + this->ui->lineEdit_deviceId->text() << __LINE__ << __FILE_NAME__;


    //         //emit UiUpdateMediator::getInstance()->updateDevice();
    //     }
    // });

    // QJsonObject jsonData;
    // jsonData["device_id"] = this->ui->lineEdit_deviceId->text();
    // if(this->ui->pushButton_connect->text() == "连接")
    // {
    //     jsonData["new_connection_status"] = 1;
    // }
    // else
    // {
    //     jsonData["new_connection_status"] = 0;
    // }

    // QJsonDocument doc(jsonData);
    // QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::deviceUpdate));
    // request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    // manager->post(*request, doc.toJson(QJsonDocument::Compact));
}

void DeviceCard::on_pushButton_setState_clicked()
{
    if(this->ui->pushButton_setState->text() == "启用")
    {
        this->ui->pushButton_setState->setText("禁用");
        this->ui->pushButton_setState->setStyleSheet(this->redButtonStyle);
        this->ui->label_isEnabled->setText("使用中");
        this->ui->label_isEnabled->setStyleSheet(this->greenFontLabel);

        QJsonObject payload;
        payload["device_id"] = this->device_info->m_deviceId;
        payload["command"] = "is_enabled=1";
        QJsonDocument doc(payload);
        qDebug() << doc;
        qDebug() << this->device_info->m_deviceId;
        MqttClient::getInstance().m_client->publish(QMqttTopicName("IOT_DM/command"), doc.toJson(QJsonDocument::Compact), 1, false);
    }
    else
    {
        this->ui->pushButton_setState->setText("启用");
        this->ui->pushButton_setState->setStyleSheet(this->greenButtonStyle);
        this->ui->label_isEnabled->setText("禁用中");
        this->ui->label_isEnabled->setStyleSheet(this->redFontLabel);

        QJsonObject payload;
        payload["device_id"] = this->device_info->m_deviceId;
        payload["command"] = "is_enabled=0";
        QJsonDocument doc(payload);
        qDebug() << doc;
        qDebug() << this->device_info->m_deviceId;
        MqttClient::getInstance().m_client->publish(QMqttTopicName("IOT_DM/command"), doc.toJson(QJsonDocument::Compact), 1, false);
    }

    // QNetworkAccessManager* manager = new QNetworkAccessManager();
    // connect(manager, &QNetworkAccessManager::finished, this,[=](QNetworkReply* reply){
    //     int stateCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    //     if(stateCode == 200)
    //     {
    //         if(this->ui->pushButton_setState->text() == "启用")
    //         {
    //             this->ui->pushButton_setState->setText("禁用");
    //             this->ui->pushButton_setState->setStyleSheet(this->redButtonStyle);
    //             this->ui->label_isEnabled->setText("使用中");
    //             this->ui->label_isEnabled->setStyleSheet(this->greenFontLabel);
    //         }
    //         else
    //         {
    //             this->ui->pushButton_setState->setText("启用");
    //             this->ui->pushButton_setState->setStyleSheet(this->greenButtonStyle);
    //             this->ui->label_isEnabled->setText("禁用中");
    //             this->ui->label_isEnabled->setStyleSheet(this->redFontLabel);
    //         }

    //         qDebug() << "设备修改成功" + this->ui->lineEdit_deviceId->text() << __LINE__ << __FILE_NAME__;
    //         //emit UiUpdateMediator::getInstance()->updateDevice();
    //     }
    // });

    // QJsonObject jsonData;
    // jsonData["device_id"] = this->ui->lineEdit_deviceId->text();
    // if(this->ui->pushButton_setState->text() == "启用")
    // {
    //     jsonData["new_is_enabled"] = 1;
    // }
    // else
    // {
    //     jsonData["new_is_enabled"] = 0;
    // }

    // QJsonDocument doc(jsonData);
    // QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::deviceUpdate));
    // request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    // manager->post(*request, doc.toJson(QJsonDocument::Compact));
}

